package com.bblocks.Interceptor;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.bblocks.common.Constant;
import com.bblocks.enums.AppPlatformTypeEnum;
import com.bblocks.enums.IdentityEnum;
import com.bblocks.util.TraceIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor {
	
	//private final static String ACCESS_TOKEN = "accessToken";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader(Constant.ACCESS_TOKEN_KEY);

		String uri = request.getRequestURI();
		String traceId = request.getHeader(TraceIdUtils.TRACE_ID);
		if(StrUtil.isNotEmpty(traceId)) {
			TraceIdUtils.setTraceId(traceId);
		}else{
			TraceIdUtils.setTraceId(IdentityEnum.Inner.name(),uri,null);//String.valueOf(System.currentTimeMillis())
		}
		MDC.put(Constant.ACCESS_TOKEN_KEY, accessToken);

		/**
		 * 提取app基础信息
		 */
		initAppInfoByHead(request);

        return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		//调用结束后删除
        //MDC.remove(ACCESS_TOKEN);
		MDC.clear();
	}

	/**
	 *  提取app基础信息（目前只做了appType）
	 * @param request
	 */
	private void initAppInfoByHead(HttpServletRequest request){
		/**
		 *  目前主要提取 YZ-APPTYPE,以及通过UserAgent来判断
		 */
		String appType = request.getHeader(Constant.AppHead.HEAD_APPTYPE);

		AppPlatformTypeEnum platformTypeEnum = null;
		if(StrUtil.isNotEmpty(appType) && NumberUtil.isInteger(appType)) {
			platformTypeEnum = AppPlatformTypeEnum.getAppPlatformTypeEnum(NumberUtil.parseInt(appType));
			//request.setAttribute(Constant.AppHead.HEAD_APPTYPE, AppPlatformTypeEnum.getAppPlatformTypeEnum(NumberUtil.parseInt(appType)));
		}else{//默认android 吧
			//request.setAttribute(Constant.AppHead.HEAD_APPTYPE, AppPlatformTypeEnum.getAppPlatformTypeEnum(null));
			String userAgent = request.getHeader("User-Agent");
			/**
			 * UserAgent范例：
			 * 小程序(ios)
			 * UserAgent:Mozilla/5.0 (iPhone; CPU iPhone OS 15_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.20(0x18001441) NetType/4G Language/zh_CN
			 *
			 * 小程序(android 小米k40)
			 * UserAgent:Mozilla/5.0 (Linux; Android 11; M2012K10C Build/RP1A.200720.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/86.0.4240.99 XWEB/3225 MMWEBSDK/20220204 Mobile Safari/537.36 MMWEBID/1217 MicroMessenger/8.0.20.2100(0x28001455) Process/toolsmp WeChat/arm64 Weixin NetType/5G Language/zh_CN ABI/arm64
			 *
			 * app（ios）
			 * UserAgent:yue zhu/1.3.5 (iPhone; iOS 15.4.1; Scale/3.00)
			 *
			 *
			 * app(android)
			 * UserAgent:okhttp/3.14.9
			 */
			if(StrUtil.isNotEmpty(userAgent)){
				if(userAgent.indexOf("yue zhu") != -1 && userAgent.indexOf("iPhone") != -1){
					platformTypeEnum = AppPlatformTypeEnum.Ios;
				}else if(userAgent.indexOf("okhttp/3.14.9") != -1){
					platformTypeEnum = AppPlatformTypeEnum.Android;
				}else if(userAgent.toLowerCase().indexOf("micromessenger") != -1){//目前通过判定 MicroMessenger，来确认是否微信访问吧（不是太准确）
					platformTypeEnum = AppPlatformTypeEnum.Wx;
				}
			}
		}

		if(platformTypeEnum == null)
			platformTypeEnum = AppPlatformTypeEnum.Unknown;

		request.setAttribute(Constant.AppHead.HEAD_APPTYPE, platformTypeEnum);

		String cityCode = request.getHeader(Constant.CITY_CODE);
		if(StrUtil.isNotEmpty(cityCode))
			request.setAttribute(Constant.CITY_CODE, cityCode);
	}

}
